import { atom, AtomEffect } from 'recoil';

const localStorageEffect = <T>(key: string): AtomEffect<T> => ({setSelf, onSet}) => {
  const savedValue = localStorage.getItem(key);
  if (savedValue != null) {
    setSelf(JSON.parse(savedValue));
  }

  onSet((newValue) => {
    localStorage.setItem(key, JSON.stringify(newValue));
  });
};

export const CONFIG = atom({
  key: 'CONFIG',
  default: {
    sound: true,
  },
  effects: [
    localStorageEffect<{ sound: boolean; }>('CONFIG'),
  ],
});

export const PLAY_SETTING = atom({
  key: 'PLAY_SETTING',
  default: {
    mines: 10,
    amount: 10,
    isAutoPlay: false,
  },
});

export const PLAY_DATA = atom<{
  useLattice: number[];
  autoPlayRound: number;
}>({
  key: 'PLAY_DATA',
  default: {
    useLattice: [],
    autoPlayRound: 0,
  },
});

// RoundDetailMask弹窗
export const RoundDetailMaskState = atom({
  key: 'RoundDetailMaskState',
  default: false,
});

// RoundDetailMask弹窗
export const RoundDetailState = atom({
  key: 'RoundDetailState',
  default: {},
});

// Game Rules弹窗
export const GameRulesMaskState = atom({
  key: 'GameRulesMaskState',
  default: false,
});